import { ref } from "vue";
import { defineStore } from "pinia";
import { getInfoApi, loginApi } from "@/api/login/loginApi";
import { setToken } from "@/utils/auth";
import { encrypt } from "@/utils/jsencrypt";

export const useUserStore = defineStore("user", () => {
  const userInfo = ref<any>({});
  const isLogin = ref(false);

  async function login(data: any) {
    const dataCopy = JSON.parse(JSON.stringify(data));

    dataCopy.loginPwd = encrypt(dataCopy.loginPwd);

    const { token } = await loginApi(dataCopy);
    setToken(token);

    getUserInfo();
  }

  async function getUserInfo() {
    try {
      const resp = await getInfoApi();
      userInfo.value = resp.user;
      isLogin.value = true;
    } catch (error) {
      loginOut();
    }
  }

  function loginOut() {
    setToken("");
    isLogin.value = false;
    userInfo.value = {};
  }

  return { userInfo, login, getUserInfo, isLogin, loginOut };
});
